package com.tzxs.pay.main.bill.detail;

import android.app.Activity;
import android.app.ProgressDialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.tzxs.pay.R;
import com.tzxs.pay.databinding.AutTncItemDetailBinding;
import com.tzxs.pay.main.base.BaseActivity;
import com.tzxs.pay.main.bill.detail.model.CancelAutBean;
import com.tzxs.pay.main.bill.model.AutBeanDetail;
import com.tzxs.pay.main.bill.viewmodel.BillViewModel;
import com.tzxs.pay.main.deposit.AutDetailNavigator;
import com.tzxs.pay.main.deposit.model.SettlementBean;
import com.tzxs.pay.main.gather.model.BankBean;
import com.tzxs.pay.main.gather.viewmodel.BankViewModel;
import com.tzxs.pay.main.print.utils.print.AidlUtil;
import com.tzxs.pay.util.ISharedPreference;
import com.tzxs.pay.util.StatusBarColorSetter;
import com.tzxs.pay.util.SystemUtil;
import com.tzxs.pay.util.ViewDialog;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 预授权交易未完成页面
 */
public class AutTncActivity extends BaseActivity<AutTncItemDetailBinding> {
    private static final String TAG = AutTncActivity.class.getSimpleName();
    private static final int BANK_AUT_CODE = 104;
    private BillViewModel model;
    private ProgressDialog progressDialog;
    //如果支付成功需要打印
    private BankViewModel bankViewModel;
    private Intent bankIntent;
    //预授权类型
    private String autType = "";

    @Override
    protected Activity getChildActivity() {
        return this;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.aut_tnc_item_detail;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarColorSetter.setStatusBarColor(this, Color.parseColor("#FAFAFA"));
        //初始化打印机
        AidlUtil.getInstance().initPrinter();
        model = ViewModelProviders.of(this).get(BillViewModel.class);
        bankViewModel = ViewModelProviders.of(this).get(BankViewModel.class);
        dataBinding.autTncToolbar.setTitle("");
        dataBinding.setViewModel(model);
        setSupportActionBar(dataBinding.autTncToolbar);
        //返回
        dataBinding.autTncToolbar.setNavigationOnClickListener(v -> onBackPressed());
        initIntent();//初始化调起银行卡相关参数
        dataBinding.autTncToolbar.setOnMenuItemClickListener(item -> {
            if (item.getItemId() == R.id.print) {
                print(model.autDeatil.get());
                return true;
            }
            return false;
        });
        //从上个页面获取到对象
        String orderId = getIntent().getStringExtra("orderId");
        Log.d(TAG, "onCreate: 从上个页面获取到的订单号:" + orderId);
        //获取订单详情列表
        model.getAutBillDetail(orderId, () -> {
            if (getIntent().getBooleanExtra("needPrint", false)) {
                print(model.autDeatil.get());
            }
            autType = model.autDeatil.get().getPre_auth_type();
            initPage(Objects.requireNonNull(model.autDeatil.get()));
        });
        //观察snackbar
        model.snackbarText.observe(this, s -> {
            if (s != null) {
                Toast.makeText(this, s, Toast.LENGTH_LONG).show();
            }
        });
        model.dialogText.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                if (s == null) {
                    progressDialog.dismiss();
                } else {
                    progressDialog = ProgressDialog.show(AutTncActivity.this, s, "请稍等……", false, false);
                }
            }
        });
        //观察snackbar
        bankViewModel.snackText.observe(this, s -> {
            if (s != null) {
                Toast.makeText(this, s, Toast.LENGTH_LONG).show();
            }
        });
        bankViewModel.dialogText.observe(this, s -> {
            if (s == null) {
                progressDialog.dismiss();
            } else {
                progressDialog = ProgressDialog.show(AutTncActivity.this, s, "请稍等……", false, false);
            }
        });
        //结算和预授权撤销
        dataBinding.setNavigator(new AutDetailNavigator() {
            @Override
            public void settlement() {//结算
                if (TextUtils.isEmpty(dataBinding.autTncConsumeNum.getText().toString())) {

                    Snackbar.make(dataBinding.autTncToolbar, "请输入消费金额", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(dataBinding.autTncNote.getText().toString())) {

                    Snackbar.make(dataBinding.autTncToolbar, "请输入备注信息", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                if (dataBinding.autTncOrderStatus.getText().toString().equals("结算成功")) {

                    Toast.makeText(AutTncActivity.this, "该订单已结算", Toast.LENGTH_SHORT).show();
                    return;
                }
                //调起结算的时候显示弹窗
                showSettlementDialog(dataBinding.autTncNum.getText().toString(),
                        dataBinding.autTncConsumeNum.getText().toString(),
                        dataBinding.autTncConsumeTime.getText().toString());
            }

            @Override
            public void refund() {//预授权撤销 分为银行卡 支付宝或者微信
                if (model.autDeatil.get().getUnfreeze_status() == 1) {
                    Toast.makeText(AutTncActivity.this, "该订单已经撤销", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (dataBinding.autTncOrderStatus.getText().toString().equals("结算成功")) {
                    Toast.makeText(AutTncActivity.this, "该订单已结算", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(dataBinding.autTncNote.getText().toString())) {
                    Toast.makeText(AutTncActivity.this, "备注不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                showCancelAutDialog();//显示预授权撤销dialog
            }
        });
    }

    //打印
    private void print(Object bean) {
        if (bean == null) {
            return;
        }
        List<String> printContent;
        if (bean instanceof CancelAutBean.DataBean) {//扫码预授权撤销  打印内容
            CancelAutBean.DataBean cancelAutBean = (CancelAutBean.DataBean) bean;
            printContent = Objects.requireNonNull(cancelAutBean).getPrint_array();
        } else if (bean instanceof AutBeanDetail.DataBean) {//预授权详情打印内容
            printContent = Objects.requireNonNull((AutBeanDetail.DataBean) bean).getPrint_array();
        } else {//结算打印内容
            printContent = Objects.requireNonNull((SettlementBean.DataBean) bean).getPrint_array();
        }
        // String bitmapType = printContent.get(0);
        AidlUtil aidlUtil = AidlUtil.getInstance();
        if (Build.MODEL.contains("T2")) {
            String paymentMethod = printContent.get(0);
            String filename = null;
            switch (paymentMethod) {
                case "0":
                    filename = "icon_alipay.bmp";
                    break;
                case "1":
                    filename = "icon_union.bmp";
                    break;
                case "2":
                    filename = "icon_wechat.bmp";
            }
            try {
                Bitmap bitmap = BitmapFactory.decodeStream(getAssets().open(filename));
                aidlUtil.printBitmap(bitmap, "0", "2", 0);
                aidlUtil.printText(printContent.get(1) + '\n', "32", "32",
                        "1", true, false);
                aidlUtil.printText(printContent.get(2) + '\n', "24", "24",
                        "1", false, false);
                String paymentMethodAndMore = printContent.get(3);
                paymentMethodAndMore = paymentMethodAndMore.replace("\\n", "\n");
                aidlUtil.printText(paymentMethodAndMore, "24", "24",
                        "0", false, false);
                String collection = printContent.get(6);
                collection = collection.replace("\\n", "\n");
                aidlUtil.printText(collection, "24", "24",
                        "0", false, false);
                String remarks = printContent.get(7);
                remarks = remarks.replace("\\n", "\n");
                aidlUtil.printText(remarks, "24", "24",
                        "0", false, false);
                aidlUtil.printQr(printContent.get(8), "6", "3");
                String cashierAndPrintingTime = printContent.get(9);
                cashierAndPrintingTime = cashierAndPrintingTime.replace("\\n", "\n");
                aidlUtil.printText(cashierAndPrintingTime, "24", "24",
                        "0", false, false);
                String last = printContent.get(10);
                last = last.replace("\\n", "\n");
                aidlUtil.printText(last, "24", "24",
                        "1", false, false);
                String repeat = printContent.get(12);
                aidlUtil.printText(repeat + "\n\n", "24", "24",
                        "1", false, false);
                aidlUtil.cutPaper(null);
            } catch (IOException ex) {
                Log.e(TAG, null, ex);
            }
        } else {
            aidlUtil.enterPrinterBuffer(true);
            String bitmapType = printContent.get(0);
            //打印支付方式图标
            commenPrint(printContent, aidlUtil, bitmapType);
//        aidlUtil.enterPrinterBuffer(true);
//        int resId = 0;
//        resId = getResId(bitmapType);
//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId);
//        //打印支付方式图标
//        aidlUtil.printBitmap(bitmap, "2", "2", resId);
//        //抬头
//        aidlUtil.printText(printContent.get(1), "32", "32", "1",
//                true, false);
//        aidlUtil.printBlankLine("1", "10");
//        //门店
//        aidlUtil.printText(printContent.get(2), "24", "24", "1",
//                false, false);
//        //订单支付方式text开始
//        aidlUtil.printText(printContent.get(3).replace("\\n", "\n"),
//                "24", "24", "0",
//                false, false);
//        //业务记录
//
//            aidlUtil.printText(printContent.get(4), "32", "32", "0",
//                    true, false);
//
//        //业务记录内容
//            if (!TextUtils.isEmpty(printContent.get(5))){
//                aidlUtil.printText(printContent.get(5)
//                                .replace("\\n", "\n"), "24", "24", "0",
//                        false, false);
//            }
//
//
//        //退款 ||收款
//        aidlUtil.printText(printContent.get(6), "32", "32", "0",
//                true, false);
//        //退款获取收款内容
//        aidlUtil.printText(printContent.get(7)
//                        .replace("\\n", "\n"), "24", "24", "0",
//                false, false);
//        aidlUtil.printBlankLine("1", "10");
//        //打印二维码
//        aidlUtil.printQr(printContent.get(8), "8", "3");
//        //收银员   //打印时间
//        aidlUtil.printText(printContent.get(9).replace("\\n", "\n"),
//                "24", "24", "0", false, false);
//
//        aidlUtil.printBlankLine("1", "10");
//        aidlUtil.printText(printContent.get(10).replace("\\n", "\n"),
//                "24", "24", "1", false, false);
//        aidlUtil.printText(printContent.get(11).replace("\\n", "\n"),
//                "24", "24", "1", false, false);
//        aidlUtil.printText(printContent.get(12),
//                "24", "24", "1", false, false);
//        aidlUtil.printBlankLine("3", "50");
//        aidlUtil.printCommit();
        }
    }

    //显示预授权撤销dialog
    private void showCancelAutDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.cancel_aut_dialog, null);
        TextView password = view.findViewById(R.id.pay_password);
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("预授权撤销")
                .setMessage("是否进行预授权撤销?")
                .setView(view)
                .setPositiveButton("确认", (dialog, which) -> {
                    if (TextUtils.isEmpty(password.getText().toString())) {
                        Toast.makeText(this, "请输入支付密码", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    dialog.dismiss();
                    cancelAut(password.getText().toString().trim(),
                            dataBinding.autTncNote.getText().toString());//确认后预授权撤销
                }).setNegativeButton("取消", (dialog, which) -> {
                    dialog.dismiss();
                });
        builder.show();
    }

    //撤销预授权
    private void cancelAut(String password, String remark) {
        if (autType.equals("BNAK")) {
            //银行卡预授权撤销
            bankViewModel.cancelBankAut(dataBinding.autTncOrderId.getText().toString(), () -> {
                Log.d(TAG, "refund: 银行卡预授权撤销成功!");
                //调用银行卡撤销
                startGather("14");
            });
        } else {
            //普通预授权撤销
            bankViewModel.cancelAut(model.autDeatil.get().getAuth_no(), password, remark, () -> {
                String content = "普通预授权撤销成功  ¥" + dataBinding.autTncNum.getText().toString() + " " + getCurrentTime();
                model.startGt(ISharedPreference.getInstance(getApplication()).getCid(), "天择可付推送提醒", content, () -> {
                });
                if (bankViewModel.cancelBean.get() != null) {
                    print(bankViewModel.cancelBean.get());
                    showPrintDialog2(bankViewModel.cancelBean.get());
                }
            });
        }
    }

    //获取当前时间
    private String getCurrentTime() {
        SimpleDateFormat simpleDateFormat = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
        simpleDateFormat.applyPattern("MM-dd HH:mm:SS");
        return simpleDateFormat.format(new Date());
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: 创建页面.....");
    }

    //初始化页面
    private void initPage(AutBeanDetail.DataBean bean) {
        String payStr = null;
        switch (bean.getPay_status()) {
            case 1:
                payStr = "未结算";
                break;
            case 2:
                payStr = "授权失败";
                break;
            case 3:
                payStr = "等待授权";
                break;
            case 4:
                payStr = "已结算";
                break;
            case 5:
                payStr = "已解冻退回";
                break;
        }
        //支付方式
        switch (bean.getPay_type()) {
            case "weixin":
                dataBinding.autTncType.setImageResource(R.drawable.ic_wechat);
                break;
            case "alipay":
                dataBinding.autTncType.setImageResource(R.drawable.ic_alipay);
                break;
            default:
                dataBinding.autTncType.setImageResource(R.drawable.ic_unionpay);
                break;
        }
        dataBinding.autTncOrderStatus.setText(payStr);
    }

    //开始预授权撤销
    private void startGather(String transName) {
        if (bankViewModel.bankBean != null) {
            //获取订单成功后
            BankBean.DataBean bean = bankViewModel.bankBean.get();
            if (bean != null) {
                String str = bean.getAmount();
                double du = Double.valueOf(str) * 100;
                int result = (int) du;
                Log.d(TAG, "getInfo: 最后金额结果:" + result);
                bankIntent.putExtra("barcodeType", "0");//指定为银行卡消费
                bankIntent.putExtra("amount", getAmount(String.valueOf(result)));//交易金额
                bankIntent.putExtra("orderNoSFT", bean.getOut_trade_no());//交易订单号
                bankIntent.putExtra("transName", transName);//交易类型  消费 退款   0是消费
                //用户联备注
                bankIntent.putExtra("printMerchantInfo",
                        "交易订单号:" + bean.getOut_trade_no() + "        "
                                + "\n交易备注: 银行卡预授权撤销");
                bankIntent.putExtra("printMerchantInfo2", bean.getOut_trade_no());
                bankIntent.putExtra("priInfo", "交易订单号:" + bean.getOut_trade_no() + "        "
                        + "\n交易备注:  银行卡预授权撤销");
                bankIntent.putExtra("priInfo2", bean.getOut_trade_no());
                if (isInstallShengfuPay()) {
                    startActivityForResult(bankIntent, BANK_AUT_CODE);
                } else {
                    Toast.makeText(this, "请前往应用市场下载盛付通支付!", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    //开始银行卡结算
    private void startBankSettmend(String transName) {

        //创建预授权结算订单
        bankViewModel.createBankSettmentedOrder(Double.parseDouble(dataBinding.autTncConsumeNum.getText().toString()),
                "auth", dataBinding.autTncNote.getText().toString(), 1,
                dataBinding.autTncOrderId.getText().toString(), () -> {
                    if (bankViewModel.settmentedBean != null) {
                        //获取订单成功后
                        BankBean.DataBean bean = bankViewModel.settmentedBean.get();
                        if (bean != null) {
                            String str = bean.getAmount();
                            double du = Double.valueOf(str) * 100;
                            int result = (int) du;
                            Log.d(TAG, "getInfo: 最后金额结果:" + result);
                            bankIntent.putExtra("barcodeType", "0");//指定为银行卡消费
                            bankIntent.putExtra("amount", getAmount(String.valueOf(result)));//交易金额
                            bankIntent.putExtra("orderNoSFT", bean.getOut_trade_no());//交易订单号
                            bankIntent.putExtra("transName", transName);//交易类型  消费 退款   0是消费
                            //用户联备注
                            bankIntent.putExtra("printMerchantInfo",
                                    "交易订单号:" + bean.getOut_trade_no() + "        "
                                            + "\n交易备注: 银行卡预授权结算");
                            bankIntent.putExtra("printMerchantInfo2", bean.getOut_trade_no());
                            bankIntent.putExtra("priInfo", "交易订单号:" + bean.getOut_trade_no() + "        "
                                    + "\n交易备注:  银行卡预授权结算");
                            bankIntent.putExtra("priInfo2", bean.getOut_trade_no());
                            // TODO: 2018/5/22 到时候判断调起银行卡支付机型
                            if (isInstallShengfuPay()) {
                                startActivityForResult(bankIntent, BANK_AUT_CODE);
                            } else {
                                Toast.makeText(this, "请前往应用市场下载盛付通支付!", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                });
    }

    //抽取各个交易类型公共的字段
    private Intent initIntent() {
        bankIntent = new Intent();
        bankIntent.setComponent(new ComponentName("com.shengpay.smartpos.shengpaysdk", "com.shengpay.smartpos.shengpaysdk.activity.MainActivity"));
        bankIntent.putExtra("appId", getPackageName());
        return bankIntent;
    }

    //将交易金额统一处理成12位，不足12位的在前面补0
    private String getAmount(String amount) {
        if (TextUtils.isEmpty(amount)) return null;
        while (amount.length() < 12) {
            amount = "0" + amount;
        }
        return amount;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.print_, menu);
        return true;
    }

    //显示消费结算dialog
    private void showSettlementDialog(String autMoney, String consumeMoney, String time) {
        View dialogView = getLayoutInflater().inflate(R.layout.settlement_dialog, null);
        String amount = autMoney.substring(1);
        double autM = Double.valueOf(amount);
        double cM = Double.valueOf(consumeMoney);
        if (cM > autM) {
            Toast.makeText(AutTncActivity.this, "消费金额不能超过预授权金额", Toast.LENGTH_SHORT).show();
            return;
        }
        //预授权金额
        TextView autNum = dialogView.findViewById(R.id.aut_num);
        autNum.setText(autMoney);
        //消费金额
        TextView consumeNum = dialogView.findViewById(R.id.consume_num);
        consumeNum.setText(consumeMoney);
        //消费时间
        TextView consumeTime = dialogView.findViewById(R.id.consume_time);
        consumeTime.setText(time);
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("确认结算？")
                .setView(dialogView)
                .setPositiveButton("确定", (dialog, which) -> {
                    if (autType.equals("BNAK")) {
                        Log.d(TAG, "showSettlementDialog: 进入银行卡创建订单");
                        startBankSettmend("13");
                    } else {
                        dialog.dismiss();
                        settmented();
                    }
                })
                .setNegativeButton("取消", (dialog, which) -> {
                    dialog.dismiss();
                });
        builder.show();
    }

    //结算
    private void settmented() {
        //结算
        model.normalSettlement(dataBinding.autTncSerNumber.getText().toString(),
                dataBinding.autTncConsumeNum.getText().toString(),
                dataBinding.autTncNote.getText().toString(), () -> {
                    //此处地方执行了两次
                    Log.d(TAG, "showSettlementDialog: 跳转11");
                    String content = "普通预授权结算成功  " + dataBinding.autTncNum.getText().toString() + " " + getCurrentTime();
                    model.startGt(ISharedPreference.getInstance(getApplication()).getCid(), "天择可付推送提醒", content, () -> {
                    });
                    print(model.settmentBean.get());
                    showPrintDialog(model.settmentBean.get());
                });
    }

    //显示普通预授权打印dialog
    private void showPrintDialog(SettlementBean.DataBean bean) {
        ViewDialog viewDialog = new ViewDialog();
        viewDialog.setLayoutId(R.layout.print_dialog);
        viewDialog.showViewListener(view -> {
            TextView title = view.findViewById(R.id.cancel_dialog_title);
            title.setText("结算成功,是否打印小票?");
            TextView print = view.findViewById(R.id.cancel_yes);
            TextView cancel = view.findViewById(R.id.cancel_no);
            print.setOnClickListener(v -> {
                print(bean);
            });
            cancel.setOnClickListener(v -> {
                viewDialog.dismiss();
                //结算成功后跳转到 普通订单页面
                Intent intent = new Intent(AutTncActivity.this, CollAndInstallDetailActivity.class);
                String orderId = bean.getOut_trade_no();
                String result;
                //微信返回时  返回的订单号是fu开头
                if (orderId.startsWith("fu")) {
                    result = orderId.replace("fu", "f");
                    intent.putExtra("orderId", result);
                } else {
                    intent.putExtra("orderId", orderId);
                }
                Log.d(TAG, "showPrintDialog: 订单号为:" + bean.getOut_trade_no());
                intent.putExtra("needPrint", false);
                startActivity(intent);
                finish();
            });
        });
        viewDialog.show(getSupportFragmentManager(), "0");
    }

    //显示撤销成功dialog
    private void showPrintDialog2(Object bean) {
        ViewDialog viewDialog = new ViewDialog();
        viewDialog.setLayoutId(R.layout.print_dialog);
        viewDialog.showViewListener(view -> {
            TextView title = view.findViewById(R.id.cancel_dialog_title);
            title.setText("撤销成功,是否打印小票?");
            TextView print = view.findViewById(R.id.cancel_yes);
            TextView cancel = view.findViewById(R.id.cancel_no);
            print.setOnClickListener(v -> {
                print(bean);
            });
            cancel.setOnClickListener(v -> {
                viewDialog.dismiss();
                Intent intent = new Intent(this, AutTradedDetailActivity.class);
                intent.putExtra("orderId", bankViewModel.cancelBean.get().getOut_trade_no());
                intent.putExtra("needPrint", false);
                startActivity(intent);
                finish();
            });
        });
        viewDialog.show(getSupportFragmentManager(), "0");
    }

    //处理返回结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == BANK_AUT_CODE) {//银行卡相关操作
            if (data != null) {
                Bundle bundle = data.getExtras();
                dealBankAut(resultCode, bundle, data);
            }
        }
    }

    //处理银行卡相关交易
    private void dealBankAut(int resultCode, Bundle extras1, Intent data) {
        boolean isSettmented = false;//是否是结算
        boolean success = false;//是否交易成功
        if (extras1 == null) {
            return;
        }
        String payResult = null;//交易结果
        Set<String> keySet = extras1.keySet();
        String orderId = extras1.getString("transId");
        if (Objects.requireNonNull(extras1.getString("transName")).equals("14")) {
            isSettmented = false;
        }
        if (Objects.requireNonNull(extras1.getString("transName")).equals("13")) {
            isSettmented = true;
        }
        switch (resultCode) {
            case Activity.RESULT_OK:
                Toast.makeText(AutTncActivity.this, "交易成功", Toast.LENGTH_SHORT).show();
                success = true;
                StringBuilder resultBuilder = new StringBuilder();
                for (String s : keySet) {
                    String str = s + ":" + extras1.getString(s) + ",";
                    resultBuilder.append(str);
                }
                Log.d(TAG, "onActivityResult: 支付结果：" + resultBuilder.toString());
                payResult = resultBuilder.toString();
                String content = null;
                if (Objects.requireNonNull(extras1.getString("transName")).equals("14")) {
                    content = "银行卡预授权撤销成功  ¥" + dataBinding.autTncNum.getText().toString() + " " + getCurrentTime();
                    isSettmented = false;
                }
                if (Objects.requireNonNull(extras1.getString("transName")).equals("13")) {
                    content = "银行卡结算成功  " + dataBinding.autTncNum.getText().toString() + " " + getCurrentTime();
                    isSettmented = true;
                }
                model.startGt(ISharedPreference.getInstance(getApplication()).getCid(), "天择可付推送提醒", content, () -> {

                });
                break;
            case Activity.RESULT_CANCELED:
                String reason = data.getStringExtra("reason");
                success = false;
                Toast.makeText(AutTncActivity.this, reason, Toast.LENGTH_SHORT).show();
                StringBuilder failBuilder = new StringBuilder();
                for (String s : keySet) {
                    String str = s + ":" + extras1.getString(s) + ",";
                    failBuilder.append(str);
                }
                payResult = failBuilder.toString();
                break;
        }
        Log.d(TAG, "onActivityResult:payResult :结算的交易信息======" + payResult);
        //回调上传交易结果
        boolean finalSuccess = success;
        boolean finalIsSettmented = isSettmented;
        bankViewModel.uploadTradeInfo(payResult, () -> {
            if (finalSuccess && !finalIsSettmented) {//如果交易成功  不是结算时撤销
                Intent intent = new Intent(AutTncActivity.this, AutTradedDetailActivity.class);
                intent.putExtra("orderId", orderId);
                Log.d(TAG, "dealBankAut: 银行卡预授权撤销订单号" + orderId);
                intent.putExtra("needPrint", true);
                startActivity(intent);
                finish();
            }
            //如果是交易成功并且是结算
            if (finalSuccess && finalIsSettmented) {
                Intent intent = new Intent(AutTncActivity.this, CollAndInstallDetailActivity.class);
                intent.putExtra("orderId", orderId);
                Log.d(TAG, "dealBankAut: 银行卡结算订单号" + orderId);
                intent.putExtra("needPrint", true);
                startActivity(intent);
                finish();
            }
        });
    }

    //判断是否安装盛付通支付sdk
    private boolean isInstallShengfuPay() {
        PackageManager packageManager = getPackageManager();
        List<PackageInfo> list = packageManager.getInstalledPackages(0);
        for (int i = 0; i < list.size(); i++) {
            if (SystemUtil.getSystemModel().equals("P1") || SystemUtil.getSystemModel().equals("P1_4G") || SystemUtil.getSystemModel().contains("A8")) {
                if (list.get(i).packageName.equalsIgnoreCase("sunmi.fw2.payment.shengpay") ||
                        list.get(i).packageName.equalsIgnoreCase("sunmimi.payment.shengpay") ||
                        list.get(i).packageName.equalsIgnoreCase("com.shengpay.smartpos.shengpaysdk")) {
                    return true;
                }

            }
            Log.d(TAG, "isInstallShengfuPay: 包名：" + list.get(i).packageName);
        }
        return false;
    }
}